import { Component, OnInit, Input } from '@angular/core';
import { Router }  from '@angular/router';

import { LoginService } from './login-form.service';
import { LoginForm } from './login-form.class';
import { GlobalState } from 'app/global.state';

@Component({
  selector: 'login-form',
  templateUrl: 'login-form.component.html',
  styleUrls: ['login-form.scss'],
  providers: [LoginService]
})
export class LoginFormComponent implements OnInit {
  @Input() title: string;
  @Input() url: string;
  @Input() userType: string;
  @Input() registerRouter: string;
  private directReset = '/login/reset';
  private authCodeImgDomain = '/platform/authImg';
  private authCodeImg;
  private loginForm: LoginForm;
  private loginError = false;
  private errorMsg: string;
  private loginBtn = false;
  private loading = false;

  constructor(private _loginService: LoginService,
              private _router: Router,
              private _state: GlobalState) {
  }

  ngOnInit() {
    this.updateAuthImg();
    this.loginForm = new LoginForm();
  }

  updateAuthImg() {
    this.authCodeImg = this.authCodeImgDomain + '?' + Date.now();
  }

  onSubmit() {
    this._state.userType = this.userType;
    // use local storage temporarily
    sessionStorage.setItem('userType', this.userType);
    this.loginBtn = true;
    this.loading = true;
    this.loginForm.userType = this.userType;
    this._loginService.login(this.url, this.loginForm).then(res => {
        if (res.status === 'success') {
          this._state.hasLogin = true;
          this._router.navigateByUrl('/pages/' + this.userType);
        } else {
          this.updateAuthImg();
          this.loginBtn = false;
          this._state.hasLogin = false;
          this.loginError = true;
          this.loading = false;
          this.errorMsg = res.description;
        }
      },
      error => {
        this.loginError = true;
        this.errorMsg = error;
      }
    );
  }
}
